﻿using System;
using System.ComponentModel.Composition;
using System.IO;
using Paladyne.FileSearch.Core;

namespace Paladyne.FileSearch.TxtSearchModule
{
    /// <summary>
    /// Text (.txt) files search module
    /// </summary>
    [Export(typeof (ISearchModule))]
    public class TxtSearchModuleViewModel : ISearchModule
    {
        private readonly ITextCompareStrategy _compareStrategy;

        #region Constructors

        public TxtSearchModuleViewModel(ITextCompareStrategy compareStrategy)
        {
            _compareStrategy = compareStrategy;
        }

        public TxtSearchModuleViewModel()
            : this(new DefaultTextCompareStrategy())
        {
        }

        #endregion

        #region Implementation of ISearchModule

        public string Name
        {
            get { return "Text content searcher"; }
        }

        public string Extension
        {
            get { return ".txt"; }
        }

        /// <summary>
        /// Check if file satisfies module's conditions (contains the search string)
        /// </summary>
        /// <param name="fileInfo"></param>
        /// <returns></returns>
        public bool Check(FileInfo fileInfo)
        {
            if (String.IsNullOrEmpty(SearchText))
                return true;

            bool result = false;
            using (StreamReader reader = fileInfo.OpenText())
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    if (_compareStrategy.Contains(line, SearchText, IgnoreCase))
                    {
                        result = true;
                        break;
                    }
                }
                return result;
            }
        }

        #endregion

        public string SearchText { get; set; }
        public bool IgnoreCase { get; set; }
    }
}